﻿window.addEvent('domready', function(){
	var suggest = $('suggest');
	suggest.setStyle('position', 'absolute');
	$$('input.id_L34Object').each(function(item){
		item.addEvents({
			'keyup' : function(event){
				var iKeyCode = event.keyCode;
				if (!(iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode <= 46) || (iKeyCode >= 112 && iKeyCode <= 123))) {
					var input = item;
					var value = input.value;
					var parent = item.getParent('div.place')
					if(parent == null){parent = item.getParent('tbody')}
					var id_input = parent.getChildren('input[id$=L34Object_hidden]')[0];
					if (value.length > 3){
						var parent_value = parent.getElements('select[id$=L0Object]')[0].value;
						var req = new Request({
							method: 'get',
							url: '/ajax/geography/?obj_name='+value+'&parent_name='+parent_value,
							onSuccess: function(response) {
								suggest.setStyle('display', 'block');
								suggest.getElements('li').each(function(el){el.destroy()});
								var objects = JSON.decode(response);
								for (var i in objects){
									var opt = Element('li', {'id': objects[i].id+';'+objects[i].l2_id+';'+objects[i].l1_id,'class': 'suggest_p','html': objects[i].name+'<br>',}).addEvent('click', function(event){
										input.set('value', this.innerHTML.split('<br>')[0]);
										id_input.set('value', this.id);
										suggest.setStyle('display', 'none');
									}).inject(suggest, 'top');
									if(objects[i].l2_name == null){
										add_text = objects[i].l1_name
									}else{
										add_text = objects[i].l1_name+', '+objects[i].l2_name
									}
									var addition = Element('small',{'html':	add_text}).inject(opt, 'bottom');
								}
							},
						}).send();
					}
				}
				
			},
			'focus' : function(event){
				var pos = this.getCoordinates();
				suggest.setStyle('display', 'none');
				suggest.setStyle('width', pos.width)
				suggest.setStyle('top', pos.top+pos.height);
				suggest.setStyle('left', pos.left);
			},
			//'blur' : function(event){
				//this.set('value', '')
				//suggest.setStyle('display', 'none');	    	
			//}
		})
	})
})